<template>
  <base-breadcrumb :title="breadcrumb">
    <a-card>
      <title-name title="基本信息" />
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
          <a-col :md="8" :sm="8">
            <a-form-model-item label="所属单位" prop="projectId">
              <!-- <org-tree-select 
                v-model="form.projectId" 
                :disabled="pageType === 'look' || pageType === 'change'" 
                :is-query-projec-detail="false">
              </org-tree-select> -->
              <org-tree-select v-model="form.projectId" :disabled="['look', 'change'].includes(pageType)" isAutoSelectFirst checkStrictly :is-query-projec-detail="false" @select="selectOrg"> </org-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="策划类型">
              <BaseInput v-model="form.type" type="text" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建人">
              <BaseInput v-model="form.creatorName" type="text" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :md="8" :sm="8">
            <a-form-model-item label="创建时间">
              <BaseInput v-model="form.createTime" type="text" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <!-- tool-bar -->
    <div class="tool-bar" v-if="['look'].includes(pageType)">
      <a-button type="primary" style="margin-bottom:10px" :loading="downLoading" @click="handleExport">导出全部附件</a-button>
    </div>
    <a-card>
      <title-name :title="title[activeKey - 1]" />
      <div v-loading="spinning">
        <s-table ref="table" row-key="id" :columns="columns2" :data="loadData" bordered :show-pagination="false">
          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
          <template slot="fileInfoList" slot-scope="text, record">
            <div class="uploadWrap">
              <div v-for="(item, index) in record.fileInfoList" :key="index" class="uploadName">
                <a-popover :key="item.fileId" placement="top">
                  <template slot="content">
                    <a :fileId="item.fileId" :fileName="item.fileName" :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId" target="_parent">下载</a>
                    <a-divider type="vertical" />
                    <a :key="item.fileId" @click="$filePreview(item)">查看</a>
                  </template>
                  <a-button size="small" type="link">
                    {{ item.fileName }}
                  </a-button>
                </a-popover>
                <a-icon v-if="isClose" style="cursor: pointer; margin-left: 3px" type="close" @click="deleteFiles(record.fileInfoList, index)" />
              </div>
            </div>
          </template>
          <template slot="operation" slot-scope="text, record, index">
            <MoreButton>
              <a-upload
                v-if="isClose"
                v-bind="$attrs"
                :accept="defaultAccept"
                name="file"
                :show-upload-list="false"
                :before-upload="(info, fileInfoList) => beforeUpload(info, fileInfoList, record)"
                :disabled="spinning"
                :multiple="true"
                v-on="$listeners"
                @change="info => handleChanges(info, record)"
              >
                <span style="cursor: pointer; color:#1890ff">上传附件</span>
              </a-upload>
            </MoreButton>
          </template>
        </s-table>
      </div>
    </a-card>
    <div class="page-btn-right-top">
      <a-button v-if="pageType !== 'look' && pageType !== 'change'" type="primary" :loading="submiting" @click="handleSubmit(0)" style="margin-right: 10px">
        保存草稿
      </a-button>
      <a-button v-if="pageType !== 'look'" type="primary" :loading="submiting" @click="handleSubmit(1)" style="margin-right: 10px">
        提交
      </a-button>
      <a-button @click="$close">
        关闭
      </a-button>
    </div>
  </base-breadcrumb>
</template>
<script>
import { formOption, columns2, data1, data2, data3 } from './model.js'
import { insertSelective, updateByPrimaryKeySelective, changeSelective, getStagePlanDetail } from '@/api/project/phasedPlanning'
import MoreButton from '@/components/MoreButton'
import Vue from 'vue'
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash.clonedeep'
import moment from 'moment'
import { downZip, uploadFile, deleteFile } from '@/api'
import BasePage from '@/views/basePage'

export default {
  name: 'phasedPlanningEdit' + Date.now(),
  extends: new BasePage(),
  components: {
    MoreButton
  },
  data() {
    return {
      // 面包屑名字
      breadcrumb: '',
      spinning: false,
      // 基本信息表单
      form: {
        projectId: '',
        creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name,
        createTime: moment().format('YYYY-MM-DD')
      },
      // 搜索选项
      formOption,
      // 表头
      columns2: cloneDeep(columns2),
      // 提交
      submiting: false,
      // 当前页面类型
      pageType: this.$route.query.type,
      id: this.$route.query.id,
      activeKey: this.$route.query.activeKey,
      version: this.$route.query.version,
      data: [cloneDeep(data1), cloneDeep(data2), cloneDeep(data3)],
      // 当前登录人信息
      info: Vue.getAcloudProvider().getUserInfo(),
      token: Vue.getAcloudProvider().getAccessToken(),
      isClose: this.$route.query.type !== 'look',
      files: [],
      targetColumn: null,
      businessCode: 'PM48',
      type: ['开工策划', '总承包阶段策划', '竣工策划'],
      title: ['开工策划九项关键工作', '总承包阶段十项关键工作', '竣工收尾十项关键工作'],
      defaultAccept:
        '.ceb,.ppt,.jpeg,.pptx,.xls,.xlsx,.doc,.docx,.vsd,.vsdx,.mpp,.mpt,.mov,.csv,.rtf,.wps,.et,.dps,.rar,.zip,.tar,.gz,.7z,.bz2,.bmp,.png,.jpg,.ico,.gif,.tif,.avi,.wav,.wmv,.rmvb,.mp3,.mp4,.chm,.txt,.zpet,.html,.pdf,.RAR',
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      rules: {
        projectId: [{ required: true, message: '请选择项目', trigger: 'blur' }]
      },
      downLoading: false //  导出全部附件
    }
  },
  mounted() {
    this.form.type = this.type[this.activeKey - 1]
    if (this.pageType !== 'add') {
      if (this.pageType === 'look') {
        this.columns2.splice(3, 1)
      }
      getStagePlanDetail({ stagePlanId: this.id, version: this.version }).then(res => {
        let data = res.data
        this.form.projectId = data.projectId
        if (this.pageType === 'look') {
          this.form.creatorName = data.creatorName
          this.form.createTime = data.createTime
        }
        this.data[this.activeKey - 1] = data.keyWorkList
        this.$refs['table'].refresh(true)
      })
    }
  },
  methods: {
    // 导出全部附件
    async handleExport() {
      this.downLoading = true
      const res = await this.loadData()
      this.downZip(res.data, 'fileInfoList', '批量导出').finally(() => {
        this.downLoading = false
      })
    },
    //选择单位
    selectOrg(val) {
      if (val && val.length) {
        this.form.branchComId = val[val.length - 2].orgId
        this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName }
      }
    },
    /**
     * @description: 表格数据加载方法
     * @param {void}
     * @return {promise} 接口Promise
     */
    loadData() {
      return Promise.resolve({ code: 200, data: this.data[this.activeKey - 1] })
    },
    /**
     * @description: 提交
     * @param {number} status 状态0保存草稿，1提交
     * @return {void}
     */
    handleSubmit(status) {
      if (!this.form.projectId) {
        return this.$message.warning('请选择所属单位')
      }
      if (!this.verificationFile()) {
        return this.$message.warning('每项关键工作请至少上传一个附件')
      }
      this.handleFun(status)
    },
    /**
     * @description: 提交接口
     * @param {number} status 状态0保存草稿，1提交
     * @return {void}
     */
    handleFun(status) {
      this.submiting = true
      this.setProcessConfig = null
      this.submitApprovalConfirm(status === 1 ? this.processConfig : 6, flag => {
        if (!flag) {
          this.submiting = false
          return
        }
        let params = {
          planType: this.activeKey,
          keyWorkList: this.data[this.activeKey - 1],
          projectId: this.form.projectId,
          status
        }
        let api = null
        if (this.pageType == 'add') {
          api = insertSelective
        } else if (this.pageType == 'edit') {
          api = updateByPrimaryKeySelective
          params.id = this.id
        } else if (this.pageType == 'change') {
          api = changeSelective
          params.id = this.id
          params.version = this.version
        }
        api(params)
          .then(res => {
            if (res.data.code == 0) {
              switch (status) {
                case 0:
                  this.$message.success('保存成功')
                  break
                case 1:
                  this.$message.success('提交成功')
                  break

                default:
                  break
              }
              this.$close()
            }
          })
          .finally(() => {
            this.submiting = false
          })
      })
    },
    // 文件提交前验证
    verificationFile() {
      let data = this.data[this.activeKey - 1],
        flag = true
      for (let i = 0; i < data.length; i++) {
        if (!data[i].fileInfoList || data[i].fileInfoList.length < 1) {
          flag = false
        }
        let arr = []
        data[i].fileInfoList.map(item => {
          arr.push(item.commonId)
        })
        data[i].fileList = arr
      }
      return flag
    },
    // 删除文件
    deleteFiles(data, index) {
      data.splice(index, 1)
    },
    beforeUpload(info, fileInfoList, record) {
      this.targetColumn = record
      return false
    },
    handleChanges(info, record) {
      // 图片删除直接返回并从列表中删除当前文件
      if (this.uploadType == 'image' && this.files.length + this.uploadLists.length > info.fileInfoList.length) {
        this.uploadLists = this.uploadLists.filter(el => el.id !== info.file.id)
        return
      }
      let pass = true
      const { file } = info
      const isImg = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'video/mp4' || file.type === 'video/avi'
      if (file.size / 1024 / 1024 > 500) {
        // 附件大小校验
        // 限制文件大小为500M
        this.sizeDebounce()
        pass = false
      }
      if (this.uploadType == 'image' && !isImg) {
        // 图片附件类型校验
        this.imgDebounce()
        pass = false
      }
      if (this.needChineseName) {
        // 附件名称需要汉字校验
        let re = new RegExp('[\u4E00-\\u9FFF]+', 'g')
        if (!re.test(file.name)) {
          this.nameDebounce()
          pass = false
        }
      }
      if (pass) {
        if (this.files.length >= 10) {
          this.$message.error('附件最多可以上传10个')
          return
        }
        this.files.push(file)
        this.fileChange()
      }
    },
    /**
     * @description: 500M提示
     * @param {void}
     * @return {function}
     */
    sizeDebounce: debounce(function() {
      this.$message.error('上传文件不可超出500M')
    }, 500),
    /**
     * @description: 必须图片提示
     * @param {void}
     * @return {function}
     */
    imgDebounce: debounce(function() {
      this.$message.error('只能上传图片文件！')
    }, 500),
    /**
     * @description: 附件名弹窗提示
     * @param {void}
     * @return {function}
     */
    nameDebounce: debounce(function() {
      this.$confirm({
        title: '提示',
        content: this.errorTips ? this.errorTips : '请规范附件名称，附件名称中需含有汉字',
        okType: 'danger'
      })
    }, 500),
    /**
     * @description: 文件上传防抖
     * @param {function}
     * @return {void}
     */
    fileChange: debounce(function() {
      this.handleUploadFun()
    }, 500),
    async handleUploadFun() {
      this.spinning = true
      try {
        this.targetColumn.spinning = true
        for (let i = 0; i < this.files.length; i++) {
          await this.uploadFun(this.files[i])
        }
        this.spinning = false
      } catch (err) {
      } finally {
        this.files = []
      }
    },
    /**
     * @description: 上传函数拆分
     * @param {FormData} data
     * @return {void}
     */
    uploadFun(info) {
      return new Promise(async (resolve, reject) => {
        const data = new FormData()
        data.append('file', info)
        data.append('businessCode', this.businessCode)
        uploadFile(data)
          .then(res => {
            if (res.code === 200) {
              this.targetColumn.fileInfoList.push(res.data)
            } else {
              this.$message.warning('上传失败')
            }
            resolve()
          })
          .catch(error => {
            this.$message.warning('上传失败')
            reject(error)
          })
      })
    }
  }
}
</script>
<style scoped lang="less">
@deep: ~'>>>';

.uploadWrap {
  float: left;
  overflow: hidden;
}

.uploadName {
  float: left;
  margin-right: 20px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

/*
上传按钮禁用时css
*/
.ant-upload-disabled button {
  cursor: not-allowed;
  color: #d9d9d9;
}

.ant-upload-disabled button:hover {
  border-color: #d9d9d9;
  color: #d9d9d9;
}

.ant-upload-disabled button:active {
  border-color: #d9d9d9;
  color: #d9d9d9;
}
</style>
